package sunmi.payment.L3;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import mi.payment.R;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.Configs;
import mi.payment.constants.Params;
import mi.payment.db.PayDetailModel;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.ui.base.PageRoute;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.SharedPreferencesUtil;
import mi.payment.utils.transaction.QRCodeQueryTask;
import mi.payment.utils.transaction.QueryRetTask;
import mi.payment.utils.transaction.TransactionTask;
import sunmi.payment.ui.dialog.LoadDialog;
import sunmi.sunmiui.utils.LogUtil;

public class QueryByOnline {

    private ParentActivity mActivity;

    private PayDetail mReqPayDetail;

    public QueryByOnline(ParentActivity activity) {
        mActivity = activity;
    }

    private void getData() {
        String oriVoucherNo = Params.sL3Params.oriVoucherNo;
        boolean isLastTrade = Params.sL3Params.isLastTrade;
        int lastTradeType = Params.sL3Params.lastTradeType;

        if (oriVoucherNo != null && oriVoucherNo.length() > 0) {
            mReqPayDetail = PayDetailModel.getInstance().getPayDetailById(oriVoucherNo);
        } else if (isLastTrade && lastTradeType == 1) {
            // 最后一笔银行卡消费记录
            mReqPayDetail = PayDetailModel.getInstance().getLastBankCardConsumptionTrade();
        } else if (isLastTrade && lastTradeType == 2) {
            // 支付宝
            mReqPayDetail = PayDetailModel.getInstance().getLastQRCodeByAliPay();
        } else if (isLastTrade && lastTradeType == 3) {
            // 微信
            mReqPayDetail = PayDetailModel.getInstance().getLastQRCodeByWeChat();
        } else if (isLastTrade && lastTradeType == 4) {
            // 银联二维码
            mReqPayDetail = PayDetailModel.getInstance().getLastQRCodeByUnion();
        } else if (isLastTrade && lastTradeType == 0) {
            // 非银行卡（扫码类）
            mReqPayDetail = PayDetailModel.getInstance().getLastQRCodeConsumptionTrade();
        }
    }

    public void queryTradeByOnline() {
        getData();
        if (mReqPayDetail == null) {
            L3BroadcastHelper.sendFailedBroadcast(mActivity, L3ErrorCode.ERROR_NOT_TRADE);
            mActivity.finish();
        } else {
            if (mReqPayDetail.transPlatform == 0) {
                // 银行卡查询
                queryOrderForBankCard();
            } else {
                // 扫码类查询
                queryOrderForCode();
            }
        }
    }

    private void queryOrderForCode() {
        final TradeData oriTradeData = PayDetailModel.getInstance().getTradeDataByVoucherNo(mReqPayDetail.voucherNo);
        TradeData newTradeData = SharedPreferencesUtil.clone(oriTradeData);

        String serialNum = SystemParamsOperation.getInstance().getIncrementSerialNum();
        newTradeData.getPayDetail().setVoucherNo(serialNum);
        LogUtil.e(Configs.TAG, "voucherNo:" + serialNum);

        @SuppressLint("StaticFieldLeak")
        TransactionTask<TradeData, Void, TradeData> task = new QRCodeQueryTask(mActivity) {

            @Override
            protected void onPostExecuteImpl(TradeData tradeData) {
                if (tradeData == null) {
                    PageRoute.startAction(mActivity, PageRoute.TYPE_ORDER_QUERY, mReqPayDetail);
                    return;
                }

                PayDetail resPay = tradeData.getPayDetail();
                mReqPayDetail.setThirdTransNum(resPay.thirdTransNum);
                mReqPayDetail.setTradeResultDes(resPay.tradeResultDes);
                mReqPayDetail.setTradeAnswerCode(resPay.tradeAnswerCode);
                mReqPayDetail.setQRCodeTransState(resPay.QRCodeTransState);
                if (mReqPayDetail.referNo == null || mReqPayDetail.referNo.length() == 0) {
                    mReqPayDetail.setReferNo(resPay.referNo);
                }

                if (resPay.QRCodeTransState == 1) {
                    // mReqPayDetail 可能为状态不明的这一笔
                    boolean isCancel = false;
                    if (mReqPayDetail.transactionType == 2 || mReqPayDetail.transactionType == 3) {
                        mReqPayDetail.setIsCanceled(true);
                        isCancel = true;
                    }
                    mReqPayDetail.setIsPrinted(true);

                    // prePayDetail为状态不明的前一笔
                    String originalPOSNum = mReqPayDetail.originalPOSNum;
                    if (originalPOSNum != null && originalPOSNum.length() > 0) {
                        PayDetail prePayDetail = PayDetailModel.getInstance().getPayDetailById(originalPOSNum);
                        if (prePayDetail != null && isCancel) {
                            prePayDetail.setIsCanceled(true);
                            PayDetailModel.getInstance().update(prePayDetail);
                        }
                    }
                }

                // 更新数据库
                PayDetailModel.getInstance().update(mReqPayDetail);

                PageRoute.startAction(mActivity, PageRoute.TYPE_ORDER_QUERY, mReqPayDetail);
            }

            @Override
            protected void onTaskTimeoutImpl() {
                PageRoute.startTimeoutAction(mActivity, PageRoute.TYPE_ORDER_QUERY, mReqPayDetail);
            }

        };
        LoadDialog loadingDialog = mActivity.getLoadingDialog(R.string.load_search);
        task.setLoadDialog(loadingDialog);
        task.execute(newTradeData);
    }

    private void queryOrderForBankCard() {
        final TradeData oriTradeData = PayDetailModel.getInstance().getTradeDataByVoucherNo(mReqPayDetail.voucherNo);
        TradeData newTradeData = SharedPreferencesUtil.clone(oriTradeData);

        String serialNum = SystemParamsOperation.getInstance().getIncrementSerialNum();
        newTradeData.getPayDetail().setVoucherNo(serialNum);
        LogUtil.e(Configs.TAG, "voucherNo:" + serialNum);

        @SuppressLint("StaticFieldLeak")
        TransactionTask<TradeData, Void, TradeData> task = new QueryRetTask(mActivity) {

            @Override
            protected void onPostExecuteImpl(TradeData tradeData) {
                if (tradeData == null) {
                    PageRoute.startAction(mActivity, PageRoute.TYPE_ORDER_QUERY, mReqPayDetail);
                    return;
                }

                PayDetail resPay = tradeData.getPayDetail();
                mReqPayDetail.setThirdTransNum(resPay.thirdTransNum);
                mReqPayDetail.setTradeResultDes(resPay.tradeResultDes);
                mReqPayDetail.setTradeAnswerCode(resPay.tradeAnswerCode);
                mReqPayDetail.setQRCodeTransState(resPay.QRCodeTransState);
                if (mReqPayDetail.referNo == null || mReqPayDetail.referNo.length() == 0) {
                    mReqPayDetail.setReferNo(resPay.referNo);
                }

                boolean isSuccess = TextUtils.equals("00", resPay.tradeAnswerCode);
                if (isSuccess) {
                    // mReqPayDetail 可能为状态不明的这一笔
                    boolean isCancel = false;
                    if (mReqPayDetail.transactionType == 2 || mReqPayDetail.transactionType == 3 ||
                            mReqPayDetail.transactionType == 5 || mReqPayDetail.transactionType == 7) {
                        mReqPayDetail.setIsCanceled(true);
                        isCancel = true;
                    }
                    mReqPayDetail.setIsPrinted(true);

                    // prePayDetail为状态不明的前一笔
                    String originalPOSNum = mReqPayDetail.originalPOSNum;
                    if (originalPOSNum != null && originalPOSNum.length() > 0) {
                        PayDetail prePayDetail = PayDetailModel.getInstance().getPayDetailById(originalPOSNum);
                        if (prePayDetail != null && isCancel) {
                            prePayDetail.setIsCanceled(true);
                            PayDetailModel.getInstance().update(prePayDetail);
                        }
                    }
                }

                // 更新数据库
                PayDetailModel.getInstance().update(mReqPayDetail);

                PageRoute.startAction(mActivity, PageRoute.TYPE_ORDER_QUERY, mReqPayDetail);
            }

            @Override
            protected void onTaskTimeoutImpl() {
                PageRoute.startTimeoutAction(mActivity, PageRoute.TYPE_ORDER_QUERY, mReqPayDetail);
            }

        };
        LoadDialog loadingDialog = mActivity.getLoadingDialog(R.string.load_search);
        task.setLoadDialog(loadingDialog);
        task.execute(newTradeData);
    }


}
